<template>
    <div class="order-management-container">
        <div class="header-card">
            <h2>订单管理</h2>
            <p>管理平台订单信息</p>
        </div>

        <el-card class="table-card" shadow="never">
            <div class="toolbar">
                <div class="search-area">
                    <el-select v-model="filterShopId" placeholder="请选择商家" clearable
                        style="width: 150px; margin-right: 10px;" @change="fetchData">
                        <el-option label="全部商家" :value="null"></el-option>
                        <el-option v-for="shop in shopOptions" :key="shop.id" :label="shop.shop_name"
                            :value="shop.id" />
                    </el-select>

                    <el-select v-model="filterOrderStatus" placeholder="订单状态" clearable
                        style="width: 150px; margin-right: 10px;" @change="fetchData">
                        <el-option label="全部状态" :value="null"></el-option>
                        <el-option label="待备货" value="0"></el-option>
                        <el-option label="已支付待核销" value="1"></el-option>
                        <el-option label="已完成" value="2"></el-option>
                        <el-option label="已取消" value="3"></el-option>
                    </el-select>

                    <el-select v-model="filterVerificationStatus" placeholder="核销状态" clearable
                        style="width: 150px; margin-right: 10px;" @change="fetchData">
                        <el-option label="全部核销状态" :value="null"></el-option>
                        <el-option label="未核销" value="0"></el-option>
                        <el-option label="已核销" value="1"></el-option>
                        <el-option label="已失效" value="2"></el-option>
                    </el-select>

                    <el-date-picker v-model="dateRange" type="daterange" start-placeholder="下单开始日期"
                        end-placeholder="下单结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        style="width: 240px; margin-right: 10px;" @change="fetchData" />

                    <el-input v-model="searchKeyword" placeholder="搜索订单号/商品名称" style="width: 200px;" clearable
                        @keyup.enter="fetchData">
                        <template #append>
                            <el-button icon="el-icon-search" @click="fetchData"></el-button>
                        </template>
                    </el-input>
                </div>
            </div>

            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="订单ID" width="80" align="center" />
                <el-table-column prop="shop_name" label="商家" />
                <el-table-column prop="buyer_name" label="买家" />
                <el-table-column prop="order_amount" label="订单金额" align="center">
                    <template #default="scope">¥{{ scope.row.order_amount }}</template>
                </el-table-column>
                <el-table-column prop="order_time" label="下单时间" align="center">
                    <template #default="scope">{{ formatDate(scope.row.order_time) }}</template>
                </el-table-column>
                <el-table-column label="订单状态" align="center">
                    <template #default="scope">
                        <el-tag :type="getOrderStatusType(scope.row.order_status)">
                            {{ getOrderStatusText(scope.row.order_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="核销状态" align="center">
                    <template #default="scope">
                        <el-tag :type="getVerificationStatusType(scope.row.verification_status)">
                            {{ getVerificationStatusText(scope.row.verification_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="支付方式" align="center">
                    <template #default="scope">
                        {{ getPaymentMethodText(scope.row.payment_method) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="viewDetail(scope.row)" plain round>详情</el-button>
                        <el-button v-if="scope.row.order_status === '0'" size="small" type="danger"
                            @click="cancelOrder(scope.row)" plain round>取消</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="`订单详情 - ${detailData.order_no || ''}`" width="800px"
            :before-close="handleDialogClose">
            <el-form :model="detailData" label-width="120px" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="订单号:">
                            <span class="form-value">{{ detailData.order_no }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商家:">
                            <span class="form-value">{{ detailData.shop_name }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="买家:">
                            <span class="form-value">{{ detailData.buyer_name }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品名称:">
                            <span class="form-value">{{ detailData.goods_name }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="订单金额:">
                            <span class="form-value form-amount">¥{{ detailData.order_amount }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="支付方式:">
                            <span class="form-value">{{ getPaymentMethodText(detailData.payment_method) }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="下单时间:">
                            <span class="form-value">{{ formatDate(detailData.order_time) }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="订单状态:">
                            <el-tag :type="getOrderStatusType(detailData.order_status)">
                                {{ getOrderStatusText(detailData.order_status) }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="核销状态:">
                            <el-tag :type="getVerificationStatusType(detailData.verification_status)">
                                {{ getVerificationStatusText(detailData.verification_status) }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注:">
                    <span class="form-value">{{ detailData.remark || '无' }}</span>
                </el-form-item>

                <el-form-item label="核销码:" v-if="detailData.verification_code">
                    <span class="form-value">
                        <img :src="detailData.verification_code" alt=""></span>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" round>关闭</el-button>
                    <el-button v-if="detailData.order_status === '0'" type="danger" @click="cancelOrder(detailData)"
                        round>
                        取消订单
                    </el-button>
                    <el-button v-if="detailData.order_status === '1' && detailData.verification_status === '0'"
                        type="success" @click="verifyOrder(detailData)" round>
                        核销订单
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const searchKeyword = ref('')
const filterShopId = ref(null)
const filterOrderStatus = ref(null)
const filterVerificationStatus = ref(null)
const dateRange = ref([])

const baseUrl = 'http://localhost:8889' // 后端服务地址

// 商家选项
const shopOptions = ref([])

const detailData = ref({})

// 获取商家列表
const fetchShopOptions = async () => {
    try {
        const response = await axios.get(`${baseUrl}/api/admin/business/list`, {
            params: {
                page: 1,
                pageSize: 1000 // 获取所有商家
            }
        })

        if (response.data.code === 200) {
            shopOptions.value = response.data.data
        } else {
            ElMessage.error(response.data.message || '获取商家列表失败')
        }
    } catch (error) {
        ElMessage.error('获取商家列表失败: ' + error.message)
    }
}

const fetchData = async () => {
    loading.value = true
    try {
        const [startDate, endDate] = dateRange.value || []

        const response = await axios.get(`${baseUrl}/api/admin/order/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                ...(filterShopId.value !== null && { shop_id: filterShopId.value }),
                ...(filterOrderStatus.value !== null && { order_status: filterOrderStatus.value }),
                ...(filterVerificationStatus.value !== null && { verification_status: filterVerificationStatus.value }),
                ...(startDate && { start_date: startDate }),
                ...(endDate && { end_date: endDate }),
                ...(searchKeyword.value && { keyword: searchKeyword.value })
            }
        })

        if (response.data.code === 200) {
            tableData.value = response.data.data
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取订单列表失败')
        }
    } catch (error) {
        ElMessage.error('获取订单列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-')
}

const getOrderStatusText = (status) => {
    const statusMap = {
        '0': '待备货',
        '1': '已支付待核销',
        '2': '已完成',
        '3': '已取消'
    }
    return statusMap[status] || '未知状态'
}

const getOrderStatusType = (status) => {
    const typeMap = {
        '0': 'warning',
        '1': 'primary',
        '2': 'success',
        '3': 'danger'
    }
    return typeMap[status] || 'info'
}

const getVerificationStatusText = (status) => {
    const statusMap = {
        '0': '未核销',
        '1': '已核销',
        '2': '已失效'
    }
    return statusMap[status] || '未知状态'
}

const getVerificationStatusType = (status) => {
    const typeMap = {
        '0': 'warning',
        '1': 'success',
        '2': 'danger'
    }
    return typeMap[status] || 'info'
}

const getPaymentMethodText = (method) => {
    const methodMap = {
        '0': '微信支付',
        '1': '支付宝',
        '3': '银行卡',
        '4': '商城余额'
    }
    return methodMap[method] || '未支付'
}

const viewDetail = async (row) => {
    try {
        const response = await axios.get(`${baseUrl}/api/admin/order/${row.id}`)
        if (response.data.code === 200) {
            detailData.value = response.data.data
            dialogVisible.value = true
        } else {
            ElMessage.error(response.data.message || '获取订单详情失败')
        }
    } catch (error) {
        ElMessage.error('获取订单详情失败: ' + error.message)
    }
}

const cancelOrder = (row) => {
    ElMessageBox.confirm(
        `确定要取消订单"${row.order_no}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.put(`${baseUrl}/api/admin/order/cancel/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('订单取消成功')
                fetchData()
                if (dialogVisible.value) {
                    detailData.value.order_status = '3'
                }
            } else {
                ElMessage.error(response.data.message || '订单取消失败')
            }
        } catch (error) {
            ElMessage.error('订单取消失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消操作
    })
}

const verifyOrder = (row) => {
    ElMessageBox.confirm(
        `确定要核销订单"${row.order_no}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.put(`${baseUrl}/api/admin/order/verify/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('订单核销成功')
                fetchData()
                if (dialogVisible.value) {
                    detailData.value.verification_status = '1'
                }
            } else {
                ElMessage.error(response.data.message || '订单核销失败')
            }
        } catch (error) {
            ElMessage.error('订单核销失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消操作
    })
}

const handleDialogClose = (done) => {
    dialogVisible.value = false
    done()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchShopOptions()
    fetchData()
})
</script>

<style scoped>
.order-management-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    flex-wrap: wrap;
}

.toolbar>div {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.form-value {
    color: #606266;
}

.form-amount {
    font-weight: bold;
    color: #67c23a;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>